const path = require('path');

const express = require('express');
const bodyParser = require('body-parser');

//引入error controller
const errorController = require('./controllers/error')
const app = express();

app.set('view engine', 'ejs');
app.set('views', 'views');

const sequelize = require('./util/database')

//引入models 关联他们
const Product = require('./models/product')
const User = require('./models/user')
const Cart= require('./models/cart')
const CartItem= require('./models/cart-item')
const Order= require('./models/order')
const OrderItem= require('./models/order-item')


const adminRoutes = require('./routes/admin');
const shopRoutes = require('./routes/shop');

app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, 'public')));

//使用中间件
app.use((req,res,next)=>{
    User.findByPk(1)
        .then(user=>{
            req.user=user
            next()
        }).catch(err => console.log(err))
})


app.use('/admin', adminRoutes);
app.use(shopRoutes);


app.use(errorController.get404);
//在sync之前 我们要关联他们的models
Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
User.hasOne(Cart);
Cart.belongsTo(User);
Cart.belongsToMany(Product, { through: CartItem });
Product.belongsToMany(Cart, { through: CartItem });
Order.belongsTo(User);
User.hasMany(Order);
Order.belongsToMany(Product, { through: OrderItem });
Order.belongsToMany(Product, { through: OrderItem });
Product.belongsToMany(Order, { through: OrderItem });
sequelize
    .sync({foce:true})
    // .sync()
    .then(result => {
        // console.log(result)
        return User.findByPk(1)
    })
    .then(user => {
        if (!user) {
            return User.create({name: 'Max', email: 'test@test.com'})
        } else {
            return user
        }

    })
    .then(user=>{
        return user.createCart()

    })
    .then(cart=>{
        app.listen(3000)
    })
    .catch(err => {
        console.log(err)
    })




